package com.zhong.gang.pda.ui.action.receive.controller;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.luck.picture.lib.tools.ToastUtils;
import com.zhong.gang.applib.rx.RxManager;
import com.zhong.gang.applib.ui.ZhangKouView;
import com.zhong.gang.applib.utils.NumberUtils;
import com.zhong.gang.pda.api.Api;
import com.zhong.gang.applib.config.Config;
import com.zhong.gang.applib.ui.matching.MatchingBean;
import com.zhong.gang.pda.db.loction.LocationMessageUtils;
import com.zhong.gang.pda.db.user.UserBean;
import com.zhong.gang.pda.db.user.UserUtils;
import com.zhong.gang.applib.ui.view.ViewClickedListener;
import com.zhong.gang.pda.ui.main.MainBean;
import com.zhong.gang.pda.view.ShouFaView;
import com.zhong.gang.pda.R;
import com.zhong.gang.pda.ui.action.HuoBean;
import com.zhong.gang.pda.ui.action.receive.ReceiveAct;
import com.zhong.gang.applib.ui.matching.MatchingAct;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class ReceiveActionController extends BaseReceiveController
        implements ViewClickedListener, ShouFaView.ShouFaListener, ZhangKouView.ZhangKouListener {
    private ReceiveUpDataPersenter persenter;
    private boolean isAction = false;

    public ReceiveActionController(ReceiveAct act, int id, boolean isAction) {
        super(act, id);
        this.isAction = isAction;
        binding.shipperView.showEdt(true);
        imgController.addImgView(addImgAdapter, "", true);
        persenter = new ReceiveUpDataPersenter();
        binding.shipperView.setListener(this);
        binding.zhangkouMoneny.setAction(true);
        binding.zhangkouMoneny.setCheckStatus(false);
        binding.zhangkouMoneny.setListener(this);
        ((RadioButton) binding.radio.getChildAt(1)).setChecked(true);
    }

    @Override
    public void setScalesMsg(HuoBean data) {
        super.setScalesMsg(data);
        if (data.getOrderReceive() != null) {
            if (data.getOrderReceive().getPrintTicker() == 0)
                data.getOrderReceive().setPrintTicker(data.isPrintTicker() ? 1 : 0);
            if (data.getOrderReceive().getPrintTicker() < binding.radio.getChildCount()) {
                ((RadioButton) binding.radio.getChildAt(
                        data.getOrderReceive().getPrintTicker())).setChecked(true);
            }
            binding.shipperView.setData(data.getOrderReceive());
            imgController.addImgView(addImgAdapter, data.getOrderReceive().getPhoto());

            binding.snLayout.setVisibility(
                    TextUtils.isEmpty(data.getOrderReceive().getSn()) ? View.GONE : View.VISIBLE);
            binding.receiveSn.setText(data.getOrderReceive().getSn());
            for (HuoBean.OrderMaterialTypeDetailBean bean : data.getOrderReceive()
                                                                .getOrderMaterialTypeDetailList()) {
                binding.shouhuo.addView(bean);
            }
            binding.moneny.setEnabled(isAction);
            binding.moneny.setText(data.getOrderReceive().getTotalAmount());
            binding.kouzhaWeightEdt.setText(data.getOrderReceive().getSlagWeight() + "");
            binding.zhangkouMoneny.setCheckStatus(data.getOrderReceive().getFloatAmount() != 0);
            binding.zhangkouMoneny.setSlideText(data.getOrderReceive().getFloatType());
            binding.zhangkouMoneny.getBinding().monenyEdt.setText(
                    Math.abs(data.getOrderReceive().getFloatAmount()) + "");
        } else {
            binding.shouhuo.addView();
        }

        if (TextUtils.isEmpty(huoBean.getSecondTime())) {
            setEnabled(true);
        } else {
            setEnabled(data.getOrderReceive() == null ||
                    !data.getOrderReceive().getPhoto().startsWith("http"));
        }
    }

    private void setEnabled(boolean status) {
        binding.kouzhaWeightEdt.setEnabled(status);
        binding.shipperView.showEdt(status);
        binding.zhangkouMoneny.setEnabled(status);
        binding.sure.setVisibility(status ? View.VISIBLE : View.GONE);
        binding.shouhuo.setEnabled(status);
        if (status)
            binding.shouhuo.setListener(this);
        imgController.setNeedImg(addImgAdapter, act, status, Config.CAMREA, status);
    }


    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sure:
                if (binding.shipperView.getBean() == null) {
                    ToastUtils.s(act, "请选择货主信息");
                    return;
                }
                String weightStr = binding.shouhuo.getJsonArray();
                if (TextUtils.isEmpty(weightStr)) {
                    ToastUtils.s(act, "请选择料型类型");
                    return;
                }
                File file = imgController.getFile(addImgAdapter);
                if (file == null) {
                    ToastUtils.s(act, "请选择货物照片");
                    return;
                }
                int status = binding.zhangkouMoneny.getStatus();
                if (0 != status) {
                    double money = binding.zhangkouMoneny.getMoneny();
                    if (0 == money) {
                        ToastUtils.s(act, "请输入涨扣款金额");
                        return;
                    }
                }

                saveRevice(weightStr,
                        NumberUtils.getNumber(binding.kouzhaWeightEdt.getText().toString()),
                        file.getPath(), binding.zhangkouMoneny.getStatus());
                break;
        }
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_OK || data == null)
            return;
        if (requestCode == Config.CAMREA) {
            imgController.onActivityResult(addImgAdapter, resultCode, data);
        } else if (requestCode == Config.USER) {
            binding.shipperView.setData((MatchingBean) data.getSerializableExtra(Config.USER_IFNO));
        }
    }


    private void saveRevice(String list, double finalKouzha, String goodUrl, int status) {
        HuoBean.OrderReceiveBean orderReceiveBean = new HuoBean.OrderReceiveBean();
        orderReceiveBean.setPhoto(goodUrl);
        orderReceiveBean.setSlagWeight(finalKouzha);
        orderReceiveBean.setFloatType(status);
        orderReceiveBean.setFloatAmount(binding.zhangkouMoneny.getMoneny());
        orderReceiveBean.setFinalAmount(NumberUtils.getNumber(binding.moneny.getText().toString()));
        MatchingBean.ConsignorBean consignorBean = new MatchingBean.ConsignorBean();
        MatchingBean.ConsignorBankCardBean consignorBankCardBean =
                new MatchingBean.ConsignorBankCardBean();
        orderReceiveBean.setConsignor(consignorBean);
        orderReceiveBean.setConsignorBankCard(consignorBankCardBean);
        orderReceiveBean.setConsignor(binding.shipperView.getBean().getConsignor());
        orderReceiveBean.setConsignorBankCard(binding.shipperView.getBean().getConsignorBankCard());
        orderReceiveBean.setRemark(binding.shipperView.getRemark());
        orderReceiveBean.setRemark(binding.shipperView.getRemark());
        orderReceiveBean.setPrintTicker(getPrintTicker());
        try {
            List<HuoBean.OrderMaterialTypeDetailBean> data = new ArrayList<>();
            JSONArray array = new JSONArray(list);
            for (int n = 0; n < array.length(); n++) {
                data.add(new Gson().fromJson(array.getString(n),
                        HuoBean.OrderMaterialTypeDetailBean.class));
            }
            orderReceiveBean.setOrderMaterialTypeDetailList(data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        huoBean.setType(2);
        huoBean.setOrderReceive(orderReceiveBean);
        LocationMessageUtils.getIntent(act).saveData(huoBean);
        MainBean mainBean = new MainBean();
        mainBean.setType(2);
        mainBean.setId(huoBean.getId());
        new RxManager().post(Config.MAIN, mainBean);
        persenter.upStartData(act, huoBean, true);
    }

    @Override
    public void onViewClicked() {
        UserBean userBean = UserUtils.getIntent(act).getUser();
        MatchingAct.openAct(act, Api.getConsignorinfo, userBean.isLogin(), userBean.getToken(),
                userBean.getId() + "", userBean.getRoleId() + "", false, true, Config.USER, true);
    }

    /**
     * 获取是否打印小票
     */
    private int getPrintTicker() {
        for (int n = 0; n < binding.radio.getChildCount(); n++) {
            RadioButton radioButton = (RadioButton) binding.radio.getChildAt(n);
            if (radioButton.isChecked())
                return n;
        }
        return 1;
    }

    @Override
    public void onShowFa(double moneny) {
        binding.zhangkouMoneny.setMoneny(moneny);
    }

    @Override
    public void onZhangKou(double money) {
        if (isAction) {
            binding.moneny.setText(money + "");
        }
    }
}
